package org.jash.shop2111.home

import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import dagger.hilt.android.AndroidEntryPoint
import org.jash.shop2111.BR
import org.jash.shop2111.R
import org.jash.shop2111.databinding.FragmentHomeBinding
import org.jash.shop2111.databinding.FragmentProductBinding
import org.jash.shop2111.entry.Goods
import org.jash.shop2111.mvvm.BaseFragment
import org.jash.shop2111.product.ProductViewModel
import org.jash.shop2111.utils.CommonAdapter
import org.jash.shop2111.utils.Event

/**
 * A simple [Fragment] subclass.
 * Use the [HomeFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
@Route(path = "/shop/product")
@AndroidEntryPoint
class ProductFragment : BaseFragment<FragmentProductBinding, ProductViewModel>() {
    val adapter by lazy { CommonAdapter<Goods>({R.layout.goods_item to BR.goods}) }
    @Autowired
    @JvmField
    var cid = 0
    var page = 1
    val size = 10
    override fun initData() {
        ARouter.getInstance().inject(this)
        viewModel.goodsLiveData.observe(this) {
            if (page == 1) {
                adapter.clear()
            }
            adapter += it
            binding.refresh.closeHeaderOrFooter()
            if (it.isEmpty()) {
                Toast.makeText(requireContext(), "没有更多的产品", Toast.LENGTH_SHORT).show()
            }
        }
        page = 1
        viewModel.loadGoods(cid , page, size)
    }

    override fun initView() {
        binding.recycler.adapter = adapter
        binding.refresh.setOnRefreshListener {
            page = 1
            viewModel.loadGoods(cid , page, size)
        }
        binding.refresh.setOnLoadMoreListener {
            viewModel.loadGoods(cid , ++page, size)
        }
    }

    override fun error(throwable: Throwable) {
        super.error(throwable)
        binding.refresh.closeHeaderOrFooter()
    }
    @Event("click")
    fun show(goods: Goods) {
        Log.d("ProductFragment", "show: $goods")
        Log.d("ProductFragment", "LiveDataBus 成功")
    }
}